package com.create404.suishoupai.config.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.create404.suishoupai.entity.Employee;
import com.create404.suishoupai.service.IEmployeeService;
import com.create404.suishoupai.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
 * TODO
 *
 * @author Stephana
 * date 2021/7/21 14:47
 * @version 1.0
 * @Description 自定义realm
 */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        // 根据主身份信息获取角色信息 和 权限信息
        IEmployeeService employeeService = (IEmployeeService) ApplicationContextUtils.getBean("employeeService");
        Employee employee = employeeService.findRolesByEmployeeId(primaryPrincipal);
        //赋值授权角色
        if (!CollectionUtils.isEmpty(employee.getRoles())) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            employee.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());

            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 根据身份信息
        String principal = (String) authenticationToken.getPrincipal();
        //在工厂中获取service对象
        IEmployeeService employeeService = (IEmployeeService) ApplicationContextUtils.getBean("employeeService");

        Employee employee = employeeService.getOne(new QueryWrapper<Employee>().eq("employee_id", principal));
        if (!ObjectUtils.isEmpty(employee)) {
            return new SimpleAuthenticationInfo(employee.getEmployeeId(), employee.getPassword(), ByteSource.Util.bytes(employee.getSalt()), this.getName());
        }
        return null;
    }
}
